import subprocess
import os
import sys
import threading
import time


# =================== 工具函数 ===================

def run_script(script_name):
    """运行指定的 Python 脚本"""
    print(f"[INFO] 正在运行脚本: {script_name}")
    result = subprocess.run(['python', script_name], capture_output=True, text=True)
    if result.returncode == 0:
        print(f"[SUCCESS] 脚本 {script_name} 成功完成")
        return True
    else:
        print(f"[ERROR] 脚本 {script_name} 执行失败:")
        print(result.stderr)
        return False


# =================== GUI 监控线程 ===================

class GUIThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self.gui_process = None
        self.gui_closed = False

    def run(self):
        self.gui_process = subprocess.Popen(['python', 'GUI.py'])
        self.gui_process.wait()  # 等待 GUI 结束
        print("[INFO] GUI 窗口已关闭，准备退出主程序...")
        self.gui_closed = True

    def is_gui_closed(self):
        return self.gui_closed


# =================== 主程序逻辑 ===================

if __name__ == "__main__":
    print("[INFO] 启动主程序：自动化调度数据流")

    # Step 1: 清理环境
    run_script('clean.py')
    run_script('delete.py')

    # Step 2: 初始化数据下载与导入
    if not run_script('ossd.py'):
        print("[ERROR] OSS 数据下载失败，程序终止。")
        exit(1)

    if not run_script('dorisinsert.py'):
        print("[ERROR] Doris 数据插入失败，程序终止。")
        exit(1)

    if not run_script('mysqlinsert.py'):
        print("[ERROR] MySQL 数据插入失败，程序终止。")
        exit(1)

    run_script('delete.py')

    # Step 3: 启动 GUI
    gui_thread = GUIThread()
    gui_thread.start()

    print("[INFO] 等待 GUI 启动并可能控制 time.py ...")

    try:
        while not gui_thread.is_gui_closed():
            time.sleep(1)  # 持续等待 GUI 关闭
    except KeyboardInterrupt:
        print("[INFO] 用户中断程序")

    # Step 4: 等待 GUI 关闭
    gui_thread.join()

    print("[INFO] 主程序正常退出")
    sys.exit(0)